// pages/lamp_manager/lamp_manager.js
var app = getApp()
var selected_devNo = []
var selected_mid=[]; //单灯统计数组
var branch_selected_mid = []; //补丁，分支统计数组

Page({

  /**
   * 页面的初始数据
   */
  data: {
    devNo: '',
    branch_dev:'',
    current_info: {},
    currentIndex: 0,

    hidden: true,
    list: [],
    scrollTop: 0,
    scrollHeight: 0,

    loadgroupmid:'',
    loadgroupid:'',
    loadname:'',
    districtid:'',
    districtmid:'',
    districtname:'',
    lamp_list:[],
    branch_list:[],
    cur_devNo:-1,
    cancel_all_selected:false,
    branch_cancel_all_selected:false, //补丁 分支 取消
    selected_all:false,
    branch_selected_all:false //补丁 分支 全选
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {  
    let that = this;
    that.setData({
      loadgroupmid: options.loadgroupmid,
      loadgroupid: options.loadgroupid,
      loadname: options.loadname,
      districtid: options.districtid,
      districtmid: options.districtmid,
      districtname: options.districtname
    });

    //console.log(that.data, "that,data")  
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

    wx.request({
      url: 'https://119.3.46.145/server/loadTree?userid=' + app.globalData.userid + '&id=' + that.data.loadgroupid,
      method:'post',
      header:header,
      success:res=>{
        //console.log(res);
        //{"data":"[{\"attributes\":{\"devType\":0,\"mid\":32,\"type\":3},\"id\":300000032,\"text\":\"无锡测试\",\"iconCls\":\"light_img\"},{\"attributes\":{\"devType\":0,\"mid\":35,\"type\":3},\"id\":300000035,\"text\":\"灯0329\",\"iconCls\":\"light_img\"},{\"attributes\":{\"devType\":0,\"mid\":52,\"type\":3},\"id\":300000052,\"text\":\"new_test2659\",\"iconCls\":\"light_img\"},{\"attributes\":{\"devType\":1,\"mid\":67,\"type\":2},\"id\":300000067,\"text\":\"支路1\",\"iconCls\":\"branch_img\"}]"}
        let data = JSON.parse(res.data.data);

        if(data.length == 0){
          return;
        }

        // data.forEach(function(item, index, self){
        //   item.isSelect = false;
        // });

        //console.log(data, "data loadgroup")
        let tmp_lamp_list = [];
        let tmp_branch_list = [];

        data.forEach(function(item, index, self){
          item.isSelect = false;
          if (parseInt(item.attributes.devType) == 0){
            tmp_lamp_list.push(item);
          }
          else if (parseInt(item.attributes.devType) == 1) {
            tmp_branch_list.push(item);
          }
        });

       

        that.setData({
          lamp_list: tmp_lamp_list,
          branch_list:tmp_branch_list
        });
      },
      fail:error=>{

      }
    });
  },

  add_lamp:function(){
    let that = this;
    if(that.data.currentIndex == 0){
      wx.navigateTo({
        url: '../new_lamp/new_lamp?loadgroupmid=' + that.data.loadgroupmid + '&loadgroupid=' + that.data.loadgroupid + '&loadname=' + that.data.loadname + '&districtid=' + that.data.districtid + '&districtmid=' + that.data.districtmid + '&districtname=' + that.data.districtname
      })
    }

    if (that.data.currentIndex == 1) {
      wx.navigateTo({
        url: '../new_branch/new_branch?loadgroupmid=' + that.data.loadgroupmid + '&loadgroupid=' + that.data.loadgroupid + '&loadname=' + that.data.loadname + '&districtid=' + that.data.districtid + '&districtmid=' + that.data.districtmid + '&districtname=' + that.data.districtname
      })
    }   
  },


  mod_lamp:function(e){
    let that = this;
    
    if(that.data.currentIndex == 0){
      let lampmid = e.currentTarget.dataset.mid;
      let lampid = e.currentTarget.dataset.id;

      wx.navigateTo({
        url: '../edit_lamp/edit_lamp?districtid=' + that.data.districtid + '&districtmid=' + that.data.districtmid + '&loadgroupid=' + that.data.loadgroupid + '&loadgroupmid=' + that.data.loadgroupmid + '&lampid=' + lampid + '&lampmid=' + lampmid
      })
    }

    if(that.data.currentIndex == 1){
      let branchmid = e.currentTarget.dataset.mid;
      let branchid = e.currentTarget.dataset.id;

      wx.navigateTo({
        url: '../edit_branch/edit_branch?districtid=' + that.data.districtid + '&districtmid=' + that.data.districtmid + '&loadgroupid=' + that.data.loadgroupid + '&loadgroupmid=' + that.data.loadgroupmid + '&branchid=' + branchid + '&branchmid=' + branchmid
      })
    }

    // that.setData({
    //   loadgroupmid: options.loadgroupmid,
    //   loadgroupid: options.loadgroupid,
    //   loadname: options.loadname,
    //   districtid: options.districtid,
    //   districtmid: options.districtmid,
    //   districtname: options.districtname
    // });
  },

  del_lamp:function(e){   
    //DeleteDevice
    let that = this;
   

    //第一步获取改设备的devNo
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

    //单灯
    if(that.data.currentIndex == 0){
      let lampid = e.currentTarget.dataset.id;
      let lampmid = e.currentTarget.dataset.mid;
      let tmp_lamp_list = that.data.lamp_list;
      // let cur_devNo = -1;

      wx.request({
        url: 'https://119.3.46.145/server/FindSingleLight?id=' + lampmid,
        method: 'POST',
        header: header,
        success: res => {
          //console.log(res, "res");
          //{"data":"[{\"LightType\":\"2\",\"MaxCurrent\":\"100.0\",\"turnOfftime\":\"05:00:00\",\"devNo\":\"868221043829715\",\"groupID\":\"1\",\"MinCurrent\":\"50.0\",\"Latitude\":\"32.3763\",\"Longitude\":\"119.387566\",\"Name\":\"无锡测试\",\"RatedPower\":\"0.0\",\"LightNo\":\"\",\"UserId\":\"922aeb81-29c8-41ba-9f82-36d9abb33265\",\"LightBrand\":\"\",\"id\":\"32\",\"turnOntime\":\"01:00:00\"}]"}   
          let result = JSON.parse(res.data.data)[0];

          that.setData({
            devNo: result.devNo
          });

          wx.request({
            url: 'https://119.3.46.145/server/DeleteSingleLight?userid=' + app.globalData.userid + '&devNo=' + that.data.devNo + '&id=' + lampmid,
            method: 'post',
            header: header,
            success: res => {
              //console.log(res);
              wx.showModal({
                title: '提示',
                content: res.data.info,
                success: function () {
                  if (res.data.error == '0') { //删除成功
                    //重新setData数据            
                    let tmp_lamp_list = that.data.lamp_list;
                    try {
                      tmp_lamp_list.forEach(function (item, index, self) {
                        if (item.id == lampid) {  //id指那一长串数字 100000001 20000001
                          self.splice(index, 1);
                          // console.log(index, "index");
                          throw new Error("ending");//报错，就跳出循环
                        }
                        // console.log("test foreach");
                      });
                    } catch (e) {
                      if (e.message == "ending") {
                        // log("结束了");
                      }
                    }

                    that.setData({
                      lamp_list: tmp_lamp_list
                    });
                  }
                }
              })
            },
            fail: error => {

            }
          });


        },
        fail: function (error) {
          //console.log(error, "FindSingleLight error");
          wx.showModal({
            title: '提示',
            content: error
          });
        }
      })
    }

    //分支
    if (that.data.currentIndex == 1) {
      let branchid = e.currentTarget.dataset.id;
      let branchmid = e.currentTarget.dataset.mid;
      let tmp_branch_list = that.data.lamp_list;
      // let cur_devNo = -1;

      wx.request({
        url: 'https://119.3.46.145/server/FindBranch?id=' + branchmid,
        method: 'POST',
        header: header,
        success: res => {
         
          //{"data":"{\"auto\":\"1\",\"MaxCurrent\":\"300.0\",\"turnOfftime\":\"7:0:00\",\"devNo\":\"101101101101\",\"UserId\":\"922aeb81-29c8-41ba-9f82-36d9abb33265\",\"groupID\":\"1\",\"MinCurrent\":\"150.0\",\"Latitude\":\"32.39476\",\"id\":\"87\",\"Longitude\":\"119.43214\",\"turnOntime\":\"17:29:00\",\"Name\":\"branch101\"}"}
          let result = JSON.parse(res.data.data);
          //console.log(result, "result");

          that.setData({
            branch_devNo: result.devNo
          });         

          wx.request({
            url: 'https://119.3.46.145/server/DeleteBranch',
            data:{
                userid:app.globalData.userid,
                devNo:that.data.branch_devNo,
                id:branchmid
            },
            method: 'post',
            header: header,
            success: res => {
              //console.log(res);
              wx.showModal({
                title: '提示',
                content: res.data.info,
                success: function () {
                  if (res.data.error == '0') { //删除成功
                    //重新setData数据            
                    let tmp_branch_list = that.data.branch_list;
                    try {
                      tmp_branch_list.forEach(function (item, index, self) {
                        if (item.id == branchid) {  //id指那一长串数字 100000001 20000001
                          self.splice(index, 1);
                          // console.log(index, "index");
                          throw new Error("ending");//报错，就跳出循环
                        }
                        // console.log("test foreach");
                      });
                    } catch (e) {
                      if (e.message == "ending") {
                        // log("结束了");
                      }
                    }

                    that.setData({
                      branch_list: tmp_branch_list
                    });

                    // console.log(that.data.branch_list, 'that.data.branch_list');

                    //此方法不能用，列表使用loadTree请求到的简单信息有id，mid等信息，而FindAllBranch返回的是可编辑页面的详细信息，但完全没有id，mid等信息，只有devNo，auto，maxcurrent， mincurrent等信息，只能用循环遍历已有数据
                    // wx.request({
                    //   url: 'https://119.3.46.145/server/FindAllBranch',
                    //   header:header,
                    //   method:'post',
                    //   data:{
                    //     groupID: that.data.loadgroupmid
                    //   },
                    //   success:res=>{
                    //     console.log(res, res);
                    //   }
                    // })
                  }
                }
              })
            },
            fail: error => {

            }
          });
        },
        fail: function (error) {
          //console.log(error, "FindSingleLight error");
          wx.showModal({
            title: '提示',
            content: error
          });
        }
      })
    }
    
  },

  selectApply:function (e) {
    let that = this;
    let index = e.currentTarget.dataset.index;
    let currentItem = that.data.currentIndex; //根据这个值判断 是swiper的那个部分
    //let  item = that.data.lamp_list[index];  
    let item = {};
    //单灯
    if (currentItem == 0){
      item = that.data.lamp_list[index];  
    }
    //支路
    if (currentItem == 1){
      item = that.data.branch_list[index];  
    }

    let mid = e.currentTarget.dataset.mid;     
   
    item.isSelect = !item.isSelect;
    

    //单灯
    if (currentItem == 0) {
      that.setData({
        lamp_list: that.data.lamp_list,
      });

      if (item.isSelect == true) {
        //判断在线列表中是否存在该设备，不在添加
        if (selected_mid.indexOf(mid) === -1) {
          selected_mid.push(mid);
        }
      }

      if (item.isSelect == false) {
        //判断不在线列表是否存在该设备,在就删除
        if (selected_mid.indexOf(mid) !== -1) {
          selected_mid.splice(selected_mid.indexOf(mid), 1);
        }
      }
    }
    //支路
    if (currentItem == 1) {
      that.setData({
        branch_list: that.data.branch_list,
      });

      if (item.isSelect == true) {
        //判断在线列表中是否存在该设备，不在添加
        if (branch_selected_mid.indexOf(mid) === -1) {
          branch_selected_mid.push(mid);
        }
      }

      if (item.isSelect == false) {
        //判断不在线列表是否存在该设备,在就删除
        if (branch_selected_mid.indexOf(mid) !== -1) {
          branch_selected_mid.splice(branch_selected_mid.indexOf(mid), 1);
        }
      }
    }
  },

  selectedApply_all:function(e){
    let that = this;

    if(that.data.currentIndex == 0){
      let tmp_selected_all = that.data.selected_all;
      // let tmp_cancel_all_selected = that.data.cancel_all_selected;
      that.setData({
        selected_all: !tmp_selected_all,
        // cancel_all_selected: !tmp_cancel_all_selected
      });

      if (that.data.selected_all == true) {
        that.setData({
          cancel_all_selected: false
        });
      }

      let tmp_lamp_list = that.data.lamp_list;
      tmp_lamp_list.forEach(function (item, index, self) {
        if (item.isSelect == false) {
          item.isSelect = true;
        }
      })

      that.setData({
        lamp_list: tmp_lamp_list
      });

      //先置空
      selected_mid = [];
      that.data.lamp_list.forEach(function (item, index, self) {
        selected_mid.push(item.attributes.mid);
      });
    }

    if(that.data.currentIndex == 1){
      let tmp_branch_selected_all = that.data.branch_selected_all;
     
      that.setData({
        branch_selected_all: !tmp_branch_selected_all,
        // cancel_all_selected: !tmp_cancel_all_selected
      });

      if (that.data.branch_selected_all == true) {
        that.setData({
          branch_cancel_all_selected: false
        });
      }

      let tmp_branch_list = that.data.branch_list;
      tmp_branch_list.forEach(function (item, index, self) {
        if (item.isSelect == false) {
          item.isSelect = true;
        }
      })

      that.setData({
        branch_list: tmp_branch_list
      });

      //先置空
      branch_selected_mid = [];
      that.data.branch_list.forEach(function (item, index, self) {
        branch_selected_mid.push(item.attributes.mid);
      });
    }    
  },

  cancel_selectedApply_all:function(e){
    let that = this;

    if(that.data.currentIndex ==0){
      let tmp_cancel_all_selected = that.data.cancel_all_selected;
      that.setData({
        cancel_all_selected: !tmp_cancel_all_selected
      });

      if (that.data.cancel_all_selected == true) {
        that.setData({
          selected_all: false
        });
      }

      let tmp_lamp_list = that.data.lamp_list;
      tmp_lamp_list.forEach(function (item, index, self) {
        if (item.isSelect == true) {
          item.isSelect = false;
        }
      })

      that.setData({
        lamp_list: tmp_lamp_list
      });

      selected_mid = [];
    }

    if(that.data.currentIndex == 1){
      //branch_cancel_all_selected
      let tmp_branch_cancel_all_selected = that.data.branch_cancel_all_selected;
      that.setData({
        branch_cancel_all_selected: !tmp_branch_cancel_all_selected
      });

      if (that.data.branch_cancel_all_selected == true) {
        that.setData({
          branch_selected_all: false
        });
      }

      let tmp_branch_list = that.data.branch_list;
      tmp_branch_list.forEach(function (item, index, self) {
        if (item.isSelect == true) {
          item.isSelect = false;
        }
      })

      that.setData({
        branch_list: tmp_branch_list
      });

      branch_selected_mid = [];
    }
  
   
  },

  bat_modify:function(){
    let that = this;
    if(that.data.currentIndex == 0){
      if (selected_mid.length == 0) {
        wx.showModal({
          title: '提示',
          content: "暂无选中的设备",
          show_cancel: false
        });

        return;
      }
      wx.navigateTo({
        url: '../bat_actor/bat_actor?selected_mid=' + selected_mid+'&type=0',
      })
    }

    if(that.data.currentIndex == 1){
      if (branch_selected_mid.length == 0) {
        wx.showModal({
          title: '提示',
          content: "暂无选中的支路",
          show_cancel: false
        });

        return;
      }
      wx.navigateTo({
        url: '../bat_actor/bat_actor?branch_selected_mid=' + branch_selected_mid+'&type=1',
      })
    }
   
  },
  
  //转到灯的状态控制页面
  show_lamp:function(e){
    let that = this;
    let lampid = e.currentTarget.dataset.id;
    let lampmid = e.currentTarget.dataset.mid;

    wx.navigateTo({
      url: '../singlelamp_asset/singlelamp_asset?mid=' + lampmid
    })
  },

//跳转到分支页面
  show_branch:function(e){
    let that =this;
    let mid = e.currentTarget.dataset.mid;
    let id = e.currentTarget.dataset.id;
    let districtid = e.currentTarget.dataset.districtid;
    let districtmid = e.currentTarget.dataset.districtmid;
    let loadgroupmid = e.currentTarget.dataset.loadgroupmid;
    let loadgroupid = e.currentTarget.dataset.loadgroupid;
    let branchname = e.currentTarget.dataset.branchname;

    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }
 
    //let loadName = e.currentTarget.dataset.loadname;

    //首先获取branch devNo
    wx.request({
      url: 'https://119.3.46.145/server/FindBranch?id=' + mid,
      method: 'POST',
      header: header,
      success: res => {

        //{"data":"{\"auto\":\"1\",\"MaxCurrent\":\"300.0\",\"turnOfftime\":\"7:0:00\",\"devNo\":\"101101101101\",\"UserId\":\"922aeb81-29c8-41ba-9f82-36d9abb33265\",\"groupID\":\"1\",\"MinCurrent\":\"150.0\",\"Latitude\":\"32.39476\",\"id\":\"87\",\"Longitude\":\"119.43214\",\"turnOntime\":\"17:29:00\",\"Name\":\"branch101\"}"}
        let result = JSON.parse(res.data.data);
        //console.log(result, "result");

        that.setData({
          branch_devNo: result.devNo
        });


        wx.navigateTo({
          url: '../branch_manager/branch_manager?loadgroupmid=' + loadgroupmid + "&loadgroupid=" + loadgroupid + '&districtid=' + districtid + '&districtmid=' + districtmid + '&districtname=' + that.data.districtname + '&loadname=' + that.data.loadname + '&branchname=' + branchname + '&mid=' + mid + '&id=' + id + '&devNo=' + result.devNo
        });        
      },
      fail: function (error) {
        //console.log(error, "FindSingleLight error");
        wx.showModal({
          title: '提示',
          content: error
        });
      }
    })
  },

  titleClick: function (e) {
    let that = this;
    let header = {
      'content-type': 'application/x-www-form-urlencoded',
      'cookie': "openid=" + app.globalData.openid
    }

    //页面变量全部重置
    this.setData({
      //拿到当前索引并动态改变
      currentIndex: e.currentTarget.dataset.idx
    })  
  },

  pagechange: function (e) {
    //console.log(e, "e");
    if ("touch" === e.detail.source) {
      let currentPageIndex = this.data.currentIndex
      currentPageIndex = (currentPageIndex + 1) % 2
      //console.log(currentPageIndex, "currentPageIndex");
      this.setData({
        currentIndex: currentPageIndex
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})